<?php

class FacebookConnect extends CComponents
{
	public $id;
	public $token;
	public $loginUrl;
	public $logoutUrl;
	public $facebook;
	public $user;
	
	private $appId = '420533834625111';
	private $secret = 'c3e81963686ce6cea61b0f76b25beafa';
	private $cookie = true;
	
	public function __construct()
	{
		Yii::import('pla2apiv1.extensions.facebook.SFacebook');
		$this->facebook = new SFacebook(array(
				'appId'  => $this->appId,
				'secret' => $this->secret,
				'cookie' => $this->cookie,
		));
		$this->id = $this->facebook->getUser();
			
		if($user_id){
			$logoutUrl = $this->facebook->getLogoutUrl();
			$user = $this->facebook->api('/'.$user_id);
		}else{
			$loginUrl = $sfacebook->getLoginUrl(array(
					'scope'		=> 'user_birthday,user_activities,user_location,user_relationships,
					,read_friendlists,read_insights,read_mailbox,read_requests,friends_online_presence', // Permissions to request from the user
					'redirect_uri'	=> 'http://pla2.com/user/index', // URL to redirect the user to once the login/authorization process is complete.
			));
		}
		
		if($user_id){
			$queries = array(
					array('method' => 'GET', 'relative_url' => '/'.$user_id),
					array('method' => 'GET', 'relative_url' => '/'.$user_id.'/home?limit=50'),
					array('method' => 'GET', 'relative_url' => '/'.$user_id.'/friends'),
					array('method' => 'GET', 'relative_url' => '/'.$user_id.'/photos?limit=6'),
			);
			try{
				$batchResponse = $sfacebook->api('?batch='.json_encode($queries), 'POST');
			}catch(Exception $o){
				error_log($o);
			}
		
			$user_info		= json_decode($batchResponse[0]['body'], TRUE);
			$feed			= json_decode($batchResponse[1]['body'], TRUE);
			$friends_list	= json_decode($batchResponse[2]['body'], TRUE);
			$photos			= json_decode($batchResponse[3]['body'], TRUE);
		
			if(isset($_POST['publish'])){
				try{
					$publishStream = $sfacebook->api("/$user_id/feed", 'post', array(
							'message'		=> 'Check out 25 labs',
							'link'			=> 'http://25labs.com',
							'picture'		=> 'http://25labs.com/images/25-labs-160-160.jpg',
							'name'			=> '25 labs',
							'caption'		=> '25labs.com',
							'description'		=> 'A Technology Laboratory. Highly Recomented technology blog.',
					));
				}catch(FacebookApiException $e){
					error_log($e);
				}
			}
		
			if(isset($_POST['status'])){
				try{
					$statusUpdate = $sfacebook->api("/$user_id/feed", 'post', array('message'=> $_POST['status']));
		
				}catch(FacebookApiException $e){
					error_log($e);
				}
			}
		}
		
		if(!isset($loginUrl)) $loginUrl = '';
		if(!isset($user_id)) $user_id = '';
		if(!isset($user)) $user = array();
	}
	
	public function getUser()
	{
		return $this->facebook->api('/'.$this->id);
	}
	
	public function getPermission()
	{
		return $this->facebook->api('/'.$this->id.'permission');
	}
}